package com.visionblue.business.ship.base

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.visionblue.business.ship.model.Results

/**
 * @author: xlh
 * @date: 2020-04-10 1:47 PM
 * @desc:
 */
abstract class BaseViewModel : ViewModel() {

    protected suspend fun <T> checkState(
        liveData: MutableLiveData<ViewState<T>>,
        result: Results<T>,
        successAction: (suspend (T?, Boolean) -> Unit)? = null,
        isLoadMore: Boolean = false
    ) {
        when (result) {
            is Results.Loading -> liveData.value = ViewState(isLoading = true)
            is Results.Success -> {
                if (successAction != null) {
                    try {
                        successAction(result.data, isLoadMore)
                    } catch (e: Exception) {
                        liveData.value = ViewState(throwable = e, isLoadMore = isLoadMore)
                    }
                } else {
                    liveData.value =
                        ViewState(data = result.data, isSuccess = true, isLoadMore = isLoadMore)
                }
            }
            is Results.Error -> {
                liveData.value =
                    ViewState(throwable = result.exception, isLoadMore = isLoadMore)
            }
        }

    }

    protected suspend fun <T, R> checkState2(
        liveData: MutableLiveData<ViewState<R>>,
        result: Results<T>,
        successAction: (suspend (T?, Boolean) -> Unit),
        isLoadMore: Boolean = false
    ) {
        when (result) {
            is Results.Loading -> liveData.value = ViewState(isLoading = true)
            is Results.Success -> {
                try {
                    successAction(result.data, isLoadMore)
                } catch (e: Exception) {
                    liveData.value = ViewState(throwable = e, isLoadMore = isLoadMore)
                }
            }
            is Results.Error -> {
                liveData.value =
                    ViewState(throwable = result.exception, isLoadMore = isLoadMore)
            }
        }

    }

}

data class ViewState<T>(
    val isLoading: Boolean = false,
    val throwable: Throwable? = null,
    val data: T? = null,
    val isSuccess: Boolean = false,
    val isLoadMore: Boolean = false
)